<template>
<div>
    <div class="title">
        <p class="renyuan">角色管理</p>
        <Modal v-model="modal1" title="新增角色"  :loading="loading" @on-ok="asyncOK" width="570" :styles="{top:'150px'}">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" >
                <Form-item class="sost1" prop="roleName">
                    <p class="tit">角色名称：</p>
                    <Input v-model="formValidate.roleName"  size="large" placeholder="未编辑" @on-blur="checkname(1,$event)" style="width:240px;font-size: 14px"></Input>
                </Form-item>
                <Form-item class="sost1" prop="roleId">
                    <p class="tit">角色编码：</p>
                    <Input v-model="formValidate.roleId"  size="large" placeholder="未编辑" @on-blur="checkname(2,$event)" style="width:240px;font-size: 14px"></Input>
                </Form-item>
                <Form-item class="sost1" prop="roleType">
                    <p class="tit">角色类型：</p>
                    <Select v-model="formValidate.roleType" clearable class="selc" style="width:240px;font-size: 14px" placeholder="未选择">
                        <Option v-for="item in roleTypeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </Form-item>
                <Form-item class="sost1" prop="roleClaasify">
                    <p class="tit">角色所属：</p>
                    <Select v-model="formValidate.roleClaasify" clearable class="selc" style="width:240px;font-size: 14px" placeholder="未选择">
                        <Option v-for="item in roleClaasifyList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </Form-item>
                <Form-item class="sost1" prop="roleDepartment">
                    <p class="tit">所属部门：</p>
                    <Select v-model="formValidate.roleDepartment" clearable class="selc selcc" style="width:240px;font-size: 14px" placeholder="未选择">
                        <Tree :data="baseData1" expand @on-select-change="selectChange"></Tree>
                    </Select>
                </Form-item>
                <Form-item  class="sost1"  style="margin-bottom:0px;" prop="menu">    
                    <p class="jues1">配置菜单：</p>
                    <Select v-model="formValidate.menu" clearable class="selc menulist" style="width:240px;font-size: 14px" placeholder="未选择">
                        <Tree :data="baseDataorg" expand @on-check-change="checkChange" show-checkbox></Tree>
                    </Select>
                </Form-item>
                <Form-item class="sost1" prop="status" style="padding-top: 20px;padding-bottom: 100px;">
                    <p class="jues1" style="float: left;">是否有效：</p>
                    <Radio-group  v-model="formValidate.status" type="button">    
                        <Radio class="ridou" label="1">
                            <span>是</span>
                        </Radio>
                        <Radio class="ridou" label="0">
                            <span>否</span>
                        </Radio>
                    </Radio-group>
                </Form-item>
            </Form>
            <div slot="footer" style="text-align: center;margin:17px 0px 0px 0px;">
                <Button id="serch1"  @click="handleSubmit_js('formValidate')" type="primary">保存</Button>
            </div>
        </Modal>
    </div>
    <div style="height: 48px;margin-top: 5px;">
        <div style="width: 340px;float: left;">
            <p class="jues" style="float:left">角色所属：</p>
            <Radio-group style="margin-left: 10px;margin-top: 18px;" v-model="filter.roleClaasify" type="button">
                <Radio class="ridou" label="">
                    <span>不限</span>
                </Radio>    
                <Radio class="ridou" label="系统角色">
                    <span>系统角色</span>
                </Radio>
                <Radio class="ridou" label="管理员">
                    <span>管理员</span>
                </Radio>
            </Radio-group>
        </div>
        <div style="float: left;width: 345px;">
            <p class="jues" style="float:left">角色类型：</p>
            <Radio-group style="margin-left: 10px;margin-top: 18px;" v-model="filter.roleType" type="button">
                <Radio class="ridou" label="">
                    <span>不限</span>
                </Radio>    
                <Radio class="ridou" label="PC角色">
                    <span>PC角色</span>
                </Radio>
                <Radio class="ridou" label="App角色">
                    <span>App角色</span>
                </Radio>
            </Radio-group>
        </div>
        <div style="float: left;width: 280px;">
            <p class="jues" style="float:left">是否有效：</p>
            <Radio-group style="margin-left: 10px;margin-top: 18px;" v-model="filter.status" type="button"> 
                <Radio class="ridou" label="">
                    <span>不限</span>
                </Radio>      
                <Radio class="ridou" label="1">
                    <span>是</span>
                </Radio>
                <Radio class="ridou" label="0">
                    <span>否</span>
                </Radio>
            </Radio-group>
        </div>
    </div>
    <div class="sosuo6">
         <div class="sost5">
            <p class="tit1">所属部门：</p>
            <Select v-model="filter.roleDepartment" clearable class="selc selcc1" style="width:280px;font-size: 14px" placeholder="未选择">
                <Tree :data="baseData" expand @on-select-change="selectChange"></Tree>
            </Select>
        </div>
        <div class="sost5">
            <p class="tit1">角色名称：</p>
            <Input  size="large" placeholder="未编辑" style="width:280px;font-size: 14px;position: relative;top: 0px;" v-model="filter.roleName" ></Input>
        </div>
        <Button class="congz"  type="primary" style="font-size: 18px;" @click="change">查询</Button>
        <span class="resert" @click="handleReset_6"  type="primary" style="font-size: 14px;">重置</span>
    </div>
    <div class="tab">
        <Button class="xinz" @click="newadd('formValidate')" type="primary" style="font-size: 18px;">新增</Button>
        <Table stripe :columns="columns7" :data="list"></Table>
    </div>
    <div class="pag">
        <Page :total="filter.total" :current="filter.pageIndex" :page-size="5" @on-change="changePage_js"></Page>
    </div>
    
</div>   
</template>
<script>
    import Base from '../common/Base.js'
    import {
        mapGetters,
        mapActions
    } from 'vuex'
    export default {
        mixins:[Base],
        data () {
            return {
                add:false,
                meun1:[],
                meuntext:[],
                baseData: [],
                baseData1: [],
                baseDataorg: [],
                click:false,
                loading: true,
                module:'users',
                check:{
                    tenantId:'',
                    roleId:'',
                    roleName:''
                },
                filter:{
                    roleClaasify:"",
                    roleName:"",
                    roleDepartment:"",
                    status:'',
                    roleType:''
                },
                formValidate: {
                    roleId:'',
                    tenantId: '',
                    roleName: '',
                    roleClaasify:'',
                    roleDepartment: '',
                    roleType: '',
                    status: '1',
                    createUser: '',
                    menuList:[],
                    menu:[]
                },
                ruleValidate: {
                    roleName: [
                        { required: true, message: '角色名称不能为空', trigger: 'blur' }
                    ],
                    roleId: [
                        { required: true, message: '角色编码不能为空', trigger: 'blur' }
                    ],
                    roleType: [
                        { required: true, message: '请选择角色类型', trigger: 'change' }
                    ],
                    roleDepartment: [
                        { required: true, message: '所属部门不能为空', trigger: 'blur' }
                    ],
                    status: [
                        { required: true, message: '请选是否有效', trigger: 'change' }
                    ],
                    roleClaasify: [
                        { required: true, message: '请选择角色所属', trigger: 'change' }
                    ]
                },
                roleClaasifyList: [
                    {
                        value: '系统角色',
                        label: '系统角色'
                    },
                    {
                        value: '管理者',
                        label: '管理者'
                    }
                ],
                roleTypeList: [
                    {
                        value: 'PC角色',
                        label: 'PC角色'
                    },
                    {
                        value: 'App角色',
                        label: 'App角色'
                    }
                ],
                columns7: [
                    {
                        title: '序号',
                        width: 60,
                        key: 'id'
                    },
                    {
                        title: '角色编码',
                        width: 120,
                        key: 'roleId'
                    },
                    {
                        title: '角色名称',
                        width: 120,
                        key: 'roleName'
                    },
                    {
                        title: '所属部门',
                        width: 140,
                        key: 'roleDepartment'
                    },
                    {
                        title: '角色所属',
                        width: 127,
                        key: 'roleClaasify'
                    },
                    {
                        title: '角色类型',
                        width: 120,
                        key: 'roleType'
                    },
                    {
                        title: '是否有效',
                        width: 60,
                        key: 'status1'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 190,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                        src:''
                                    },
                                    style: {
                                        background:"url('./static/img/xiugai.png') no-repeat center",
                                        fontWeight: '600',
                                        color:'#5b8cff',
                                        fontSize:'14px',
                                        width: '18px',
                                        height: '18px',
                                        padding: '0px 20px'
                                    },
                                    on: {
                                        click: () => {
                                            this.edit_js(params.index)
                                        }
                                    }
                                }, ''),
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                        src:''
                                    },
                                    style: {
                                        background:"url('./static/img/shixiao.png') no-repeat center",
                                        fontWeight: '600',
                                        color:'#5b8cff',
                                        fontSize:'14px',
                                        width: '18px',
                                        height: '18px',
                                        padding: '0px 20px'
                                    },
                                    on: {
                                        click: () => {
                                            this.lapse_js(params.index)
                                        }
                                    }
                                }, ''),
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                        src:''
                                    },
                                    style: {
                                        background:"url('./static/img/shanchu.png') no-repeat center",
                                        fontWeight: '600',
                                        color:'#5b8cff',
                                        fontSize:'14px',
                                        width: '18px',
                                        height: '18px',
                                        padding:' 0px 20px'
                                    },
                                    on: {
                                        click: () => {
                                            this.remove_js(params.index)
                                        }
                                    }
                                }, '')
                            ]);
                        }
                    }
                ]
            }
        },
        methods: {
            ...mapActions(['checkbasedata_store']),
            checkname(name,event){
                this.check.tenantId=this.filter.tenantId;
                if(event.target.value != ''){
                    if(name==1){
                        this.check.roleName=event.target.value
                    }else{
                        this.check.roleId=event.target.value
                    }
                    var _this = this;
                    _this.$http.post(`${_this.dmoreurl}/saRole/checkIdAndName`,_this.check).then(res => {
                        if(name==1){
                            if(res.data.code!='200'){
                                _this.$Message.error('角色名称重复！    请修改！');
                                _this.formValidate.roleName='';
                            }
                        }else{
                            if(res.data.code!='200'){
                                _this.$Message.error('角编码重复！    请修改！');
                                _this.formValidate.roleId='';
                            }
                        }
                        this.check.roleName='';
                        this.check.roleId='';
                    })
                }    
            },
            asyncOK () {
                setTimeout(() => {
                    this.modal1 = false;
                }, 1000);
            },
            change(){
                console.log(this. filter)
                var _this = this;
                _this.$http.post(`${_this.dmoreurl}/saRole/saRoleQueryList`,_this.filter)
                    .then(function(response) {
                        console.log(response)
                         _this.list = response.data.data.list;
                        _this.filter.total = response.data.data.total;
                        let length_yr=_this.list.length;
                        for( let i=0;i<length_yr;i++){
                            _this.$http.post(`${_this.dmoreurl}/saRole/saRoleQuery`,{roleId:_this.list[i]['roleId']})
                                .then(function(response) {  
                                    _this.list[i].menu=response.data.data.menuList;
                                });
                            _this.list[i]['id']=i+1;
                            if(_this.list[i]['status']=='1'){
                                _this.list[i]['status1']='是';
                            }else{
                                _this.list[i]['status1']='否';
                            }
                        }
                    });
            },
            selectChange(node) {
                console.log(node.length)
                if(node.length != '0'){
                    if(this.modal1){
                        this.formValidate.roleDepartment=node[0].title;
                        $('.selcc .ivu-select-selection .ivu-select-selected-value').html(node[0].title);
                    }else{
                        this.filter.roleDepartment=node[0].title;
                        $('.selcc1 .ivu-select-selection .ivu-select-selected-value').html(node[0].title);
                    }
                }
            },
            checkChange(node) {

                console.log(node)
                // var meun_text='';
                // _this.formValidate.menuList=[];
                // console.log(_this.formValidate.menu)
                // console.log(_this.baseData)
                // if(_this.formValidate.menu){
                //     for(let i=0;i< _this.formValidate.menu.length;i++){
                //         meun_text='{"menuId": '+_this.formValidate.menu[i]+'}';
                //         _this.formValidate.menuList.push(JSON.parse(meun_text));
                //     }
                // }
                //this.formValidate.menu=[];
                console.log(node.length)
                this.formValidate.menuList=[];
                this.menu1=[];
                if(node.length>=1){
                    let meun_text='';
                    let meuntext=[];
                    for(let i=0;i<node.length;i++){
                        //meun_text='{"menuId": '+node[i].menuId+'}';
                        meun_text=node[i].menuId;
                        this.menu1.push(JSON.parse(meun_text));
                        if(node[i].children == 0){
                            meuntext.push(node[i].title);
                        }
                    }
                    $('.menulist .ivu-select-selection .ivu-select-placeholder').css({'display':'none'});
                    $('.menulist .ivu-select-selection .ivu-select-selected-value').css({'display':'block'}).html(meuntext.join(','));
                    //console.log(this.formValidate.menu)
                }else{
                    $('.menulist .ivu-select-selection .ivu-select-placeholder').css({'display':'block'});
                    $('.menulist .ivu-select-selection .ivu-select-selected-value').css({'display':'none'});
                }
            },
            newadd(name){
                this.menu1=[];
                this.add = false;
                this.formValidate.menuList=[];
                $('.menulist .ivu-select-selection .ivu-select-placeholder').css({'display':'block'});
                $('.menulist .ivu-select-selection .ivu-select-selected-value').css({'display':'none'}).html('');
                this.baseDataorg=[];
                this.getData_jslist();
                this.modal1 = true;
                this.$refs[name].resetFields();
                Object.assign(this.$data.formValidate, this.$options.data().formValidate);
            },
            handleReset_6() {
                this.filter.roleClaasify='';
                this.filter.roleName='';
                this.filter.roleDepartment='';
                this.filter.status='';
                this.filter.roleType='';
            },
            changePage_js(page) {
                console.log(page)
                var _this = this;
                _this.filter.pageIndex = page;
                _this.getData_js();
            },
            rundel(data,orgdata){
                for(let i=0;i<data.length;i++){   
                    if(data[i].children.length >= 1){
                            data[i].checked=false; 
                            let data1=data[i].children;
                            this.rundel(data1,orgdata);
                    }else{
                            data[i].checked=false; 
                    }
                }
            },
            run(data,orgdata){
                for(let i=0;i<data.length;i++){   
                    if(data[i].children.length >= 1){
                        if(data[i].menuId==orgdata){
                            //console.log(data[i].title) 
                            data[i].checked=true; 
                        }else{
                            let data1=data[i].children;
                            this.run(data1,orgdata);
                        }
                    }else{
                        if(data[i].menuId==orgdata){
                            data[i].checked=true;
                            this.meuntext.push(data[i].title);
                            // console.log(data[i])  
                        }
                    }
                }
            },
            edit_js(index) {
                this.meuntext=[];
                //console.log(this.list[index])
                this.add = true;
                let orgdata=this.list[index].menu
                let data=this.basedata_store;
                console.log(data)
                //console.log(orgdata)
                for(let j=0;j<orgdata.length;j++){
                    let orgdata1=orgdata[j]
                    this.rundel(data,orgdata1);
                }
                for(let j=0;j<orgdata.length;j++){
                    let orgdata1=orgdata[j]
                    this.run(data,orgdata1);
                }
                //console.log(orgdata)
                // this.baseDataorg=[]
                // this.getData_jslist()
                this.$refs['formValidate'].resetFields();
                var _this = this;
                var dataObj = Object.assign({}, _this.list[index]);
                _this.modal1 = true;
                _this.formValidate = dataObj;
                _this.formValidate.menuList=[];
                $('.selcc .ivu-select-selection .ivu-select-selected-value').html(_this.formValidate.roleDepartment);
                $('.menulist .ivu-select-selection .ivu-select-selected-value').css({'display':'block'}).html(this.meuntext.join(','));
                // $('.menulist .ivu-select-selection .ivu-select-selected-value').css({'display':'block'}).html('hahah');
            }, 
            lapse_js(index) {
                var _this = this;
                var dataObj = Object.assign({}, _this.list[index]);
                dataObj.status="0";
                console.log(dataObj)
                this.$Modal.confirm({
                    title: '失效操作',
                    content: '<p>确认失效？</p>',
                    onOk: () => {
                        var meun_text='';
                        _this.formValidate=dataObj;
                        _this.formValidate.menuList=[];
                        if(_this.formValidate.menu){
                            for(let i=0;i< _this.formValidate.menu.length;i++){
                                meun_text='{"menuId": '+_this.formValidate.menu[i]+'}';
                                _this.formValidate.menuList.push(JSON.parse(meun_text));
                            }
                        }
                        console.log(_this.formValidate)
                        let deleteUrl = `${_this.dmoreurl}/saRole/saRoleUpdate`;
                        _this.$http.post(deleteUrl,dataObj)
                            .then(response => {
                                _this.getData_js()
                                this.$Message.info('该数据已失效');
                            })
                    },
                    onCancel: () => {
                        this.$Message.info('取消数据失效');
                    }
                });
                    
            },
            remove_js(index) {
                var _this = this;
                this.$Modal.confirm({
                    title: '确认删除数据',
                    content: '<p>确认删除数据</p>',
                    onOk: () => {
                        let deleteUrl = `${_this.dmoreurl}/saRole/saRoleDel`;
                        _this.$http.post(deleteUrl,{roleId:_this.list[index].roleId})
                            .then(response => {
                                _this.getData_js()
                                this.$Message.info('成功删除数据');
                            })
                    },
                    onCancel: () => {
                        this.$Message.info('取消删除数据');
                    }
                });

            },
            getData_js() {//分页查询暂定
                var _this = this;
                _this.$http.post(`${_this.dmoreurl}/saRole/saRoleQueryList`,_this.filter)
                    .then(function(response) {
                        console.log(response)
                         _this.list = response.data.data.list;
                        _this.filter.total = response.data.data.total;
                        let length_yr=_this.list.length;
                        for( let i=0;i<length_yr;i++){
                            _this.$http.post(`${_this.dmoreurl}/saRole/saRoleQuery`,{roleId:_this.list[i]['roleId']})
                                .then(function(response) {  
                                    _this.list[i].menu=response.data.data.menuList;
                                });
                            _this.list[i]['id']=i+1;
                            if(_this.list[i]['status']=='1'){
                                _this.list[i]['status1']='是';
                            }else{
                                _this.list[i]['status1']='否';
                            }
                        }
                    });
                
            },
            getData_jslist(){
                var _this = this;
                _this.$http.post(`${_this.dmoreurl}/saRole/getMenuList`,{tenantId:_this.filter.tenantId}).then(res => {//-------------id
                    _this.baseDataorg = res.data.data.root.child;
                    let str=JSON.stringify(_this.baseDataorg);
                    str=str.replace(/child/g,"children");
                    str=str.replace(/menuName/g,"title");
                    str=JSON.parse(str); 
                    _this.baseDataorg=str; 
                    this.checkbasedata_store(this.baseDataorg)  
                })
            },
            getData_jslist1(){
                var _this = this;
                _this.$http.post(`${_this.dmoreurl}/saOrg/getAll`,{tenantId:_this.filter.tenantId}).then(res => {//-------------id
                    _this.baseData = res.data.data.root.child;
                    let str=JSON.stringify(_this.baseData);
                    str=str.replace(/child/g,"children");
                    str=str.replace(/orgName/g,"title");
                    str=JSON.parse(str); 
                    str[0].expand=true;
                    _this.baseData=str; 
                    _this.baseData1=str;
                })
            },
            handleSubmit_js(name) {
                this.formValidate.tenantId=this.filter.tenantId;
                this.formValidate.createUser=this.filter.createUser;
                var _this = this;
                console.log(_this.add)
                 var meun_text='';
                // console.log(_this.formValidate.menu)
                // console.log(_this.baseData)
                if(_this.menu1.length >= 1){
                    _this.formValidate.menu=_this.menu1;
                }
                if(_this.formValidate.menu.length >= 1){
                    for(let i=0;i< _this.formValidate.menu.length;i++){
                        meun_text='{"menuId": '+_this.formValidate.menu[i]+'}';
                        _this.formValidate.menuList.push(JSON.parse(meun_text));
                    }
                }
                console.log(_this.formValidate)
                var submitUrl, submitMethods;
                if(_this.formValidate.menuList.length == 0){
                        this.$Message.error('请选择配置菜单!');
                        return false;
                };
                if (_this.add) {
                    submitUrl = `${_this.dmoreurl}/saRole/saRoleUpdate`;
                    submitMethods = 'POST';
                    console.log('updata')
                } else {
                    submitUrl = `${_this.dmoreurl}/saRole/saRoleAdd`;
                    submitMethods = 'POST'
                    console.log('new')
                 }
                _this.$refs[name].validate((valid) => {
                    if (valid) {
                        console.log(_this.formValidate)
                        _this.$http({
                                url: submitUrl,
                                method: submitMethods,
                                data: _this.formValidate
                            })
                            .then(function(response) {
                                if(response.data){
                                _this.$Message.success('提交成功!');
                                _this.modal1 = false;
                                _this.getData_js();
                                Object.assign(_this.$data.formValidate, _this.$options.data().formValidate); // 让我们的数据恢复到初始化状态 
                                }else{
                                    _this.$Message.success('用户名重复！    请修改！');
                                }  
                            }).catch((error) => {
                                if (error) {
                                    this.$Message.info(error.response.msg);
                                }
                            });
                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                })
            }
        },
        computed: {
            ...mapGetters(['basedata_store'])
        },
        updated(){
            $('.ivu-tree-arrow').trigger("click")
        },
        created() {
            this.getData_js();
            this.getData_jslist();
            this.getData_jslist1();
            this.formValidate.tenantId=this.filter.tenantId;
            this.formValidate.createUser=this.filter.createUser;
        }
    }
    // <div class="tabb">
    //     <span class="tabc">菜单</span>
    //     <span class="tabc">分配</span>
    //     <span class="tabc">操作</span>
    // </div>
    // <Form-item class="tabb1" >
    //     <Form-item style="width:500px;padding-top: 10px;" prop="">
    //         <span class="tabd">流程审批</span>
    //         <Checkbox-group v-model="formValidate.menu" style="display:inlin-block">
    //             <Checkbox label="1001" style="color:white;padding-right: 114px;"></Checkbox>
    //             <Checkbox label="1002" style="color:white;"></Checkbox>
    //         </Checkbox-group>
    //     </Form-item>
    // </Form-item>
    // <Form-item class="tabb2" >
    //     <Form-item style="width:500px;padding-top: 10px;" prop="">
    //         <span class="tabd">客户管理</span>
    //         <Checkbox-group v-model="formValidate.menu" style="display:inlin-block">
    //             <Checkbox label="1003" style="color:white;padding-right: 114px;"></Checkbox>
    //             <Checkbox label="1004" style="color:white;"></Checkbox>
    //         </Checkbox-group>
    //     </Form-item>
    // </Form-item>
</script>
<style lang="scss" >
    .ivu-form-item{
        margin-bottom: 15px;
    }
    .tabd{
        float: left;
        font-size: 14px;
        color: black;
        padding: 0px 134px 0px 50px;
    }
    .tabb{
        padding: 3px 35px 0px 35px;
        display: flex;
        justify-content: space-around;
        width:510px;
        height:40px;
        background: #f6f8fc;
        border: 1px solid #dbe3f3;
    }
    .tabb1{
        padding: 3px 35px 0px 35px;
        display: flex;
        justify-content: space-around;
        width:510px;
        height:60px;
    }
    .tabb2{
        padding: 3px 35px 0px 35px;
        display: flex;
        justify-content: space-around;
        width:510px;
        height:60px;
        background:#fafcff;
    }
    .tabc{
        color:#848996;
        font-size: 14px;
    }
    .sost1{
        display: inline-block;
        width: 265px;
        padding-left: 16px;
    }
    .sost2{
        padding-left: 16px;
    }
    .jues1{
        color: #848996;
        font-size: 14px;
    }
    .ridou{
        color:#34363c;
        font-size:14px;
        padding-right: 20px;
    }
</style>